package com.loopstack.gprint.io;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.SystemClock;
import android.util.Log;

import com.loopstack.gprint.utils.CallbackListener;
import com.loopstack.gprint.utils.Command;
import com.loopstack.gprint.utils.HexUtils;
import com.loopstack.gprint.utils.LogUtils;
import com.loopstack.gprint.io.PortManager;
import com.loopstack.gprint.io.PrinterDevices;
import com.loopstack.gprint.utils.SDKUtils;
import com.loopstack.gprint.utils.UIThreadManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class UsbPort extends PortManager {
    private static final String TAG = UsbPort.class.getSimpleName();
    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    private UsbDevice mUsbDevice;
    private UsbManager usbManager;
    private Context mContext;
    private UsbDeviceConnection mmConnection;
    private UsbInterface mmIntf;
    private UsbEndpoint mmEndIn;
    private UsbEndpoint mmEndOut;
    private int SPLITE_SIZE = 256;
    private boolean isConn = false;
    private Command command = null;
    private CallbackListener callbackListener;
    private PrinterDevices mPrinterDevices = null;
    private final Object lock = new Object();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    private byte[] buffer = new byte[128];
    private IoReader reader = null;

    private PendingIntent mPermissionIntent;

    public UsbPort(PrinterDevices devices) {


        if (devices != null) {
            this.mPrinterDevices = devices;
            this.mContext = devices.getContext();
            this.mUsbDevice = devices.getUsbDevice();
            this.callbackListener = devices.getCallbackListener();
            this.command = devices.getCommand();
            this.registerReceiver(this.mContext);
        }

    }

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(this.getClass().getName(), action);
            if ("com.android.example.USB_PERMISSION".equals(action)) {
                synchronized(this) {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra("device");
                    UsbPort.this.mUsbDevice = device;
                    if (intent.getBooleanExtra("permission", false)) {
                        Log.e(UsbPort.TAG, "Allow USB Permission");
                        (new Thread(new Runnable() {
                            public void run() {
                                UsbPort.this.openPort();
                            }
                        })).start();
                    } else {
                        Log.e(UsbPort.TAG, "permission denied for accessory ");
                        UsbPort.this.setFailureListen();
                    }
                }
            } else if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
                Log.e(UsbPort.TAG, "USB Device Detached");
                UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra("device");
                if (usbDevice.equals(UsbPort.this.mUsbDevice) && UsbPort.this.callbackListener != null) {
                    UIThreadManager.onUIThread(new Runnable() {
                        public void run() {
                            UsbPort.this.callbackListener.onDisconnect();
                        }
                    });
                }
            }

        }
    };


    private void registerReceiver(Context context) {
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("com.android.example.USB_PERMISSION");
            filter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
            context.registerReceiver(this.mUsbReceiver, filter);
        } catch (Exception var3) {
            LogUtils.e(var3.getMessage());
        }

    }

//    public UsbPort(Context context, int pid, int vid, CallbackListener callbackListener, Command command) {
//        class NamelessClass_1 extends BroadcastReceiver {
//            NamelessClass_1() {
//            }
//
//            public void onReceive(Context context, Intent intent) {
//                String action = intent.getAction();
//                Log.d(this.getClass().getName(), action);
//                if ("com.android.example.USB_PERMISSION".equals(action)) {
//                    synchronized(this) {
//                        UsbDevice device = (UsbDevice)intent.getParcelableExtra("device");
//                        UsbPort.this.mUsbDevice = device;
//                        if (intent.getBooleanExtra("permission", false)) {
//                            Log.e(UsbPort.TAG, "Allow USB Permission");
//                            (new Thread(new Runnable() {
//                                public void run() {
//                                    UsbPort.this.openPort(context);
//                                }
//                            })).start();
//                        } else {
//                            Log.e(UsbPort.TAG, "permission denied for accessory ");
//                            UsbPort.this.setFailureListen();
//                        }
//                    }
//                } else if ("android.hardware.usb.action.USB_DEVICE_DETACHED".equals(action)) {
//                    Log.e(UsbPort.TAG, "USB Device Detached");
//                    UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra("device");
//                    if (usbDevice.equals(UsbPort.this.mUsbDevice) && UsbPort.this.callbackListener != null) {
//                        UIThreadManager.onUIThread(new Runnable() {
//                            public void run() {
//                                UsbPort.this.callbackListener.onDisconnect();
//                            }
//                        });
//                    }
//                }
//
//            }
//        }
//
//        this.mUsbReceiver = new NamelessClass_1();
//        this.mContext = context;
//        this.callbackListener = callbackListener;
//        this.command = command;
//        this.usbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
//        HashMap deviceList = this.usbManager.getDeviceList();
//        Iterator deviceIterator = deviceList.values().iterator();
//
//        while(deviceIterator.hasNext()) {
//            UsbDevice usbDevice = (UsbDevice)deviceIterator.next();
//            if (usbDevice.getVendorId() == vid && usbDevice.getProductId() == pid) {
//                this.mUsbDevice = usbDevice;
//                break;
//            }
//        }
//
//    }

    @Override
    public boolean openPort() {
        if (this.usbManager == null) {
            this.usbManager = (UsbManager)this.mContext.getSystemService(Context.USB_SERVICE);
        }

        if (this.mUsbDevice != null) {
            if (this.callbackListener != null) {
                UIThreadManager.onUIThread(new Runnable() {
                    public void run() {
                        UsbPort.this.callbackListener.onConnecting();
                    }
                });
            }

            if (!this.usbManager.hasPermission(this.mUsbDevice)) {
                Log.e(TAG, "USB is not permission");
                this.mPermissionIntent = PendingIntent.getBroadcast(this.mContext, 0, new Intent("com.android.example.USB_PERMISSION"), 0);
                this.usbManager.requestPermission(this.mUsbDevice, this.mPermissionIntent);
            } else {
                int count = this.mUsbDevice.getInterfaceCount();
                UsbInterface intf = null;

                int i;
                for(i = 0; i < count; ++i) {
                    UsbInterface usbInterface = this.mUsbDevice.getInterface(i);
                    intf = usbInterface;
                    if (usbInterface.getInterfaceClass() == 7) {
                        break;
                    }
                }

                if (intf != null) {
                    this.mmIntf = intf;
                    this.mmConnection = null;
                    this.mmConnection = this.usbManager.openDevice(this.mUsbDevice);
                    if (this.mmConnection != null && this.mmConnection.claimInterface(intf, true)) {
                        for(i = 0; i < intf.getEndpointCount(); ++i) {
                            UsbEndpoint ep = intf.getEndpoint(i);
                            if (ep.getType() == 2) {
                                if (ep.getDirection() == 0) {
                                    this.mmEndOut = ep;
                                } else {
                                    this.mmEndIn = ep;
                                }
                            }
                        }
                    }
                }

                if (this.mmEndOut != null && this.mmEndIn != null) {
                    try {
                        if (this.command == null) {
                            this.checkPrinterCommand();
                        } else if (this.callbackListener != null) {
                            UIThreadManager.onUIThread(new Runnable() {
                                public void run() {
                                    UsbPort.this.callbackListener.onSuccess(UsbPort.this.mPrinterDevices);
                                }
                            });
                        }
                    } catch (IOException var5) {
                        this.setFailureListen();
                    }

                    this.reader = new IoReader();
                    this.reader.start();
                    this.isConn = true;
                    return true;
                }

                this.setFailureListen();
            }
        } else {
            Log.e(TAG, "USB devices is null");
            this.setFailureListen();
        }

        return false;
    }

    private void checkPrinterCommand() throws IOException {
        int status = this.getPrinterStatus(Command.ESC);
        if (status == -1) {
            status = this.getPrinterStatus(Command.CPCL);
            if (status == -1) {
                status = this.getPrinterStatus(Command.TSC);
                if (status == -1) {
                    this.setFailureListen();
                } else {
                    this.setSuccessListen(Command.TSC);
                }
            } else {
                this.setSuccessListen(Command.CPCL);
            }
        } else {
            this.setSuccessListen(Command.ESC);
        }

    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public PrinterDevices getPrinterDevices() {
        return this.mPrinterDevices;
    }

    public Command getCommand() {
        return this.command;
    }

    private void setSuccessListen(Command command) {
        this.command = command;
        this.mPrinterDevices.setCommand(command);
        if (this.callbackListener != null) {
            UIThreadManager.onUIThread(new Runnable() {
                public void run() {
                    UsbPort.this.callbackListener.onSuccess(UsbPort.this.mPrinterDevices);
                }
            });
        }

    }

    private void setFailureListen() {
        if (this.callbackListener != null) {
            UIThreadManager.onUIThread(new Runnable() {
                public void run() {
                    UsbPort.this.callbackListener.onFailure();
                }
            });
        }

    }

    public UsbDevice getmUsbDevice() {
        return this.mUsbDevice;
    }

//    @RequiresApi(
//            api = 21
//    )
//    public boolean writePDFToEsc(File file, int width) throws Exception {
//        Bitmap[] bitmaps = PDFUtils.PDFToBitmap(file, width);
//        if (bitmaps == null) {
//            return false;
//        } else {
//            for(int i = 0; i < bitmaps.length; ++i) {
//                byte[] data = PDFUtils.drawEscPDF(bitmaps[i]);
//                this.writeDataImmediately(data);
//                if (i == bitmaps.length - 1) {
//                    return true;
//                }
//            }
//
//            byte[] command = new byte[]{10, 29, 86, 66, 0, 27, 64};
//            this.writeDataImmediately(command);
//            return false;
//        }
//    }
//
//    @RequiresApi(
//            api = 21
//    )
//    public boolean writePDFToTsc(File file, int printWidth, int gap, boolean cut, boolean dpi200, boolean compression, int cutHeight) throws Exception {
//        if (file == null) {
//            throw new Exception("File cannot be empty");
//        } else if (TextUtils.isEmpty(String.valueOf(printWidth))) {
//            throw new Exception("printWidth cannot be empty");
//        } else if (TextUtils.isEmpty(String.valueOf(gap))) {
//            throw new Exception("gap cannot be empty");
//        } else if (TextUtils.isEmpty(String.valueOf(cutHeight))) {
//            throw new Exception("cutHeight cannot be empty");
//        } else {
//            Bitmap[] bitmaps = PDFUtils.PDFToBitmap(file, printWidth);
//            if (bitmaps == null) {
//                return false;
//            } else {
//                int i;
//                String cls;
//                String print;
//                if (gap > 0 | cutHeight == 0) {
//                    for(i = 0; i < bitmaps.length; ++i) {
//                        String size = "\r\nSIZE " + bitmaps[i].getWidth() / (dpi200 ? 8 : 12) + " mm," + bitmaps[i].getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
//                        this.writeDataImmediately(size.getBytes("GB18030"));
//                        String GAP = "GAP " + gap + " mm,0 mm\r\n";
//                        if (cut && i == bitmaps.length - 1) {
//                            this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
//                        } else {
//                            this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
//                        }
//
//                        this.writeDataImmediately(GAP.getBytes("GB18030"));
//                        cls = "CLS\r\n";
//                        this.writeDataImmediately(cls.getBytes("GB18030"));
//                        byte[] data;
//                        if (compression) {
//                            data = PDFUtils.drawTscPDFLib(bitmaps[i]);
//                            this.writeDataImmediately(data);
//                        } else {
//                            data = PDFUtils.drawTscPDF(bitmaps[i]);
//                            this.writeDataImmediately(data);
//                        }
//
//                        print = "\r\nPRINT 1\r\n";
//                        this.writeDataImmediately(print.getBytes("GB18030"));
//                        if (i == bitmaps.length - 1) {
//                            return true;
//                        }
//                    }
//                } else {
//                    for(i = 0; i < bitmaps.length; ++i) {
//                        List<Bitmap> mlist = ImageCrop(bitmaps[i], cutHeight);
//
//                        for(int j = 0; j < mlist.size(); ++j) {
//                            cls = "\r\nSIZE " + ((Bitmap)mlist.get(j)).getWidth() / (dpi200 ? 8 : 12) + " mm," + ((Bitmap)mlist.get(j)).getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
//                            this.writeDataImmediately(cls.getBytes("GB18030"));
//                            String GAP = "GAP 0 mm,0 mm\r\n";
//                            if (cut && j == mlist.size() - 1 && i == bitmaps.length - 1) {
//                                this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
//                            } else {
//                                this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
//                            }
//
//                            this.writeDataImmediately(GAP.getBytes("GB18030"));
//                            print = "CLS\r\n";
//                            this.writeDataImmediately(print.getBytes("GB18030"));
//                            byte[] data;
//                            if (compression) {
//                                data = PDFUtils.drawTscPDFLib((Bitmap)mlist.get(j));
//                                this.writeDataImmediately(data);
//                            } else {
//                                data = PDFUtils.drawTscPDF((Bitmap)mlist.get(j));
//                                this.writeDataImmediately(data);
//                            }
//
//                            String print = "\r\nPRINT 1\r\n";
//                            this.writeDataImmediately(print.getBytes("GB18030"));
//                        }
//
//                        if (i == bitmaps.length - 1) {
//                            mlist.clear();
//                            return true;
//                        }
//                    }
//                }
//
//                return false;
//            }
//        }
//    }
//
//    public boolean writeBitmapToTsc(Bitmap mBitmap, int printWidth, boolean cut, boolean dpi200, boolean compression, int cutHeight) throws Exception {
//        if (mBitmap == null) {
//            throw new Exception("Bitmap cannot be empty");
//        } else if (TextUtils.isEmpty(String.valueOf(printWidth))) {
//            throw new Exception("printWidth cannot be empty");
//        } else if (TextUtils.isEmpty(String.valueOf(cutHeight))) {
//            throw new Exception("cutHeight cannot be empty");
//        } else {
//            if (mBitmap != null) {
//                int width = (printWidth + 7) / 8 * 8;
//                int height = mBitmap.getHeight() * width / mBitmap.getWidth();
//                Log.d("BMP", "bmp.getWidth() " + mBitmap.getWidth());
//                Bitmap rszBitmap = GpUtils.resizeImage(mBitmap, width, height);
//                List<Bitmap> mlist = ImageCrop(rszBitmap, cutHeight);
//
//                for(int j = 0; j < mlist.size(); ++j) {
//                    String size = "\r\nSIZE " + ((Bitmap)mlist.get(j)).getWidth() / (dpi200 ? 8 : 12) + " mm," + ((Bitmap)mlist.get(j)).getHeight() / (dpi200 ? 8 : 12) + " mm\r\n";
//                    this.writeDataImmediately(size.getBytes("GB18030"));
//                    String gap = "GAP 0 mm,0 mm\r\n";
//                    this.writeDataImmediately(gap.getBytes("GB18030"));
//                    if (cut && j == mlist.size() - 1) {
//                        this.writeDataImmediately("SET CUTTER 1\r\n".getBytes("GB18030"));
//                    } else {
//                        this.writeDataImmediately("SET CUTTER OFF\r\n".getBytes("GB18030"));
//                    }
//
//                    String cls = "CLS\r\n";
//                    this.writeDataImmediately(cls.getBytes("GB18030"));
//                    byte[] data = PDFUtils.drawTscPDFLib((Bitmap)mlist.get(j));
//                    this.writeDataImmediately(data);
//                    String print = "\r\nPRINT 1\r\n";
//                    this.writeDataImmediately(print.getBytes("GB18030"));
//                    if (j == mlist.size() - 1) {
//                        return true;
//                    }
//                }
//            }
//
//            return false;
//        }
//    }

    public static List<Bitmap> ImageCrop(Bitmap bitmap, int photoheight) {
        List<Bitmap> list = new ArrayList();
        int last = bitmap.getHeight() % photoheight;

        for(int i = 0; i < bitmap.getHeight() - bitmap.getHeight() % photoheight; i += photoheight) {
            list.add(cutBitmap(bitmap, i, photoheight));
        }

        if (last > 0) {
            Bitmap cp = cutBitmap(bitmap, bitmap.getHeight() - bitmap.getHeight() % photoheight, bitmap.getHeight() % photoheight);
            list.add(cp);
        }

        return list;
    }

    public static Bitmap cutBitmap(Bitmap bitmap, int y, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Log.e(String.valueOf(w), String.valueOf(h));
        return Bitmap.createBitmap(bitmap, 0, y, w, height, (Matrix)null, false);
    }

    public boolean writeDataImmediately(Vector<Byte> sendData) throws IOException {
        if (sendData == null) {
            throw new RuntimeException("data is empty");
        } else if (this.mmConnection == null) {
            throw new IOException("no connect");
        } else {
            int offset = 0;
            byte[] data = SDKUtils.convertVectorByteToBytes(sendData);
            List<byte[]> mlist = SDKUtils.getListByteArray(data, this.SPLITE_SIZE);
            int packNum = 0;

            while(packNum < mlist.size()) {
                int ret = this.mmConnection.bulkTransfer(this.mmEndOut, (byte[])mlist.get(packNum), ((byte[])mlist.get(packNum)).length, 1000);
                Log.e(TAG, "send result" + ret);
                if (ret > 0) {
                    offset += ret;
                    ++packNum;
                } else {
                    Log.e(TAG, "send error");

                    try {
                        Thread.sleep(50L);
                    } catch (InterruptedException var8) {
                        var8.printStackTrace();
                    }
                }

                if (!this.isConn) {
                    Log.e(TAG, "Interrupt transmission");
                    break;
                }
            }

            sendData.clear();
            mlist.clear();
            if (offset == data.length) {
                Log.e(TAG, "send success");
                return true;
            } else {
                return false;
            }
        }
    }

    public boolean writeDataImmediately(byte[] data) throws IOException {
        if (data == null) {
            throw new RuntimeException("data is empty");
        } else if (this.mmConnection == null) {
            throw new IOException("no connect");
        } else {
            int offset = 0;
            List<byte[]> mlist = SDKUtils.getListByteArray(data, this.SPLITE_SIZE);
            int packNum = 0;

            while(packNum < mlist.size()) {
                int ret = this.mmConnection.bulkTransfer(this.mmEndOut, (byte[])mlist.get(packNum), ((byte[])mlist.get(packNum)).length, 1000);
                Log.e(TAG, "send result" + ret);
                if (ret > 0) {
                    offset += ret;
                    ++packNum;
                } else {
                    Log.e(TAG, "send error");

                    try {
                        Thread.sleep(50L);
                    } catch (InterruptedException var7) {
                    }
                }

                if (!this.isConn) {
                    Log.e(TAG, "Interrupt transmission");
                    break;
                }
            }

            mlist.clear();
            if (offset == data.length) {
                Log.e(TAG, "send success");
                return true;
            } else {
                return false;
            }
        }
    }

    public int getPower() throws IOException {
        byte[] command = new byte[]{31, 27, 31, -88, 16, 17, 18, 19, 20, 21, 119};
        this.writeDataImmediately(command);
        synchronized(this.lock) {
            if (this.byteArrayOutputStream.size() > 0) {
                this.byteArrayOutputStream.reset();
            }
        }

        long endTime = SystemClock.uptimeMillis() + 2000L;
        int len = -1;
        byte[] recv = new byte[1];
        if (this.reader == null) {
            do {
                if (this.mmEndIn == null) {
                    throw new IOException("Please connect Printer first...");
                }

                len = this.mmConnection.bulkTransfer(this.mmEndIn, recv, recv.length, 2000);
                if (len > 0) {
                    break;
                }

                try {
                    Thread.sleep(100L);
                } catch (InterruptedException var10) {
                }
            } while(endTime > SystemClock.uptimeMillis());
        } else {
            synchronized(this.lock) {
                while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                    try {
                        this.lock.wait(500L);
                    } catch (InterruptedException var9) {
                    }
                }

                if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                    len = this.byteArrayOutputStream.size();
                    recv = this.byteArrayOutputStream.toByteArray();
                }
            }

            if (recv != null) {
                LogUtils.e("model length" + len + "\thex:\t" + HexUtils.byte2HexStr(recv));
            }
        }

        if (len > 0) {
            if (recv[0] == 49) {
                return 1;
            }

            if (recv[0] == 50) {
                return 2;
            }

            if (recv[0] == 51) {
                return 3;
            }

            if (recv[0] == 52) {
                return 4;
            }

            if (recv[0] == 53) {
                return 5;
            }
        }

        return -1;
    }

    public String getPrinterModel(Command command) throws IOException {
        if (command == null) {
            return "";
        } else {
            synchronized(this.lock) {
                if (this.byteArrayOutputStream.size() > 0) {
                    this.byteArrayOutputStream.reset();
                }
            }

            switch (command) {
                case ESC:
                    byte[] esc = new byte[]{29, 73, 67};
                    this.writeDataImmediately(esc);
                    break;
                case TSC:
                    byte[] tsc = new byte[]{126, 33, 84, 13, 10};
                    this.writeDataImmediately(tsc);
                    break;
                case CPCL:
                    byte[] cpcl = new byte[]{27, 118};
                    this.writeDataImmediately(cpcl);
            }

            long endTime = SystemClock.uptimeMillis() + 2000L;
            int len = -1;
            byte[] recv = new byte[32];
            if (this.reader == null) {
                do {
                    if (this.mmEndIn == null) {
                        throw new IOException("Please connect Printer first...");
                    }

                    len = this.mmConnection.bulkTransfer(this.mmEndIn, recv, recv.length, 2000);
                    if (len > 0) {
                        break;
                    }

                    try {
                        Thread.sleep(100L);
                    } catch (InterruptedException var10) {
                    }
                } while(endTime > SystemClock.uptimeMillis());
            } else {
                synchronized(this.lock) {
                    while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                        try {
                            this.lock.wait(500L);
                        } catch (InterruptedException var9) {
                        }
                    }

                    if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                        len = this.byteArrayOutputStream.size();
                        recv = this.byteArrayOutputStream.toByteArray();
                    }
                }

                if (recv != null) {
                    LogUtils.e("model length" + len + "\thex:\t" + HexUtils.byte2HexStr(recv));
                }
            }

            return len > 0 ? new String(SDKUtils.subBytes(recv, 0, len)) : "";
        }
    }

    public byte[] getKey() throws IOException {
        synchronized(this.lock) {
            if (this.byteArrayOutputStream.size() > 0) {
                this.byteArrayOutputStream.reset();
            }
        }

        String command = "READ_INFO ID\r\n";
        this.writeDataImmediately(command.getBytes("GB18030"));
        long endTime = SystemClock.uptimeMillis() + 5000L;
        int len = -1;
        byte[] recv = new byte[32];
        if (this.reader == null) {
            do {
                if (this.mmEndIn == null) {
                    throw new IOException("Please connect Printer first...");
                }

                len = this.mmConnection.bulkTransfer(this.mmEndIn, recv, recv.length, 2000);
                if (len > 0) {
                    break;
                }

                try {
                    Thread.sleep(100L);
                } catch (InterruptedException var10) {
                }
            } while(endTime > SystemClock.uptimeMillis());
        } else {
            synchronized(this.lock) {
                while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                    try {
                        this.lock.wait(500L);
                    } catch (InterruptedException var9) {
                    }
                }

                if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                    len = this.byteArrayOutputStream.size();
                    recv = this.byteArrayOutputStream.toByteArray();
                }
            }

            if (recv != null) {
                LogUtils.e("model length" + len + "\thex:\t" + HexUtils.byte2HexStr(recv));
            }
        }

        if (len > 0) {
            Log.e(TAG, "加密：\t" + HexUtils.byte2HexStr(recv));
            return SDKUtils.subBytes(recv, 0, len);
        } else {
            return null;
        }
    }

    public int getPrinterStatus(Command command) throws IOException {
        if (this.mmEndOut != null && this.mmEndIn != null) {
            if (command == null) {
                return -1;
            } else {
                synchronized(this.lock) {
                    if (this.byteArrayOutputStream.size() > 0) {
                        this.byteArrayOutputStream.reset();
                    }
                }

                synchronized(this) {
                    switch (command) {
                        case ESC:
                            byte[] esc = new byte[]{16, 4, 2};
                            this.mmConnection.bulkTransfer(this.mmEndOut, esc, esc.length, 1000);
                            break;
                        case TSC:
                            byte[] tsc = new byte[]{27, 33, 63, 13, 10};
                            this.mmConnection.bulkTransfer(this.mmEndOut, tsc, tsc.length, 1000);
                            break;
                        case CPCL:
                            byte[] cpcl = new byte[]{27, 104};
                            this.mmConnection.bulkTransfer(this.mmEndOut, cpcl, cpcl.length, 1000);
                    }

                    long endTime = SystemClock.uptimeMillis() + 2000L;
                    int len = -1;
                    byte[] buffer = new byte[1];
                    if (this.reader == null) {
                        do {
                            if (this.mmEndIn == null) {
                                throw new IOException("Please connect Printer first...");
                            }

                            len = this.mmConnection.bulkTransfer(this.mmEndIn, buffer, buffer.length, 2000);
                            if (len > 0) {
                                break;
                            }

                            try {
                                Thread.sleep(100L);
                            } catch (InterruptedException var12) {
                            }
                        } while(endTime > SystemClock.uptimeMillis());
                    } else {
                        synchronized(this.lock) {
                            while(this.byteArrayOutputStream.size() == 0 && endTime > SystemClock.uptimeMillis()) {
                                try {
                                    this.lock.wait(500L);
                                } catch (InterruptedException var11) {
                                }
                            }

                            if (this.byteArrayOutputStream != null && this.byteArrayOutputStream.size() > 0) {
                                len = this.byteArrayOutputStream.size();
                                buffer = this.byteArrayOutputStream.toByteArray();
                            }
                        }

                        if (buffer != null) {
                            LogUtils.e("model length" + len + "\thex:\t" + HexUtils.byte2HexStr(buffer));
                        }
                    }

                    if (len > 0) {
                        LogUtils.e(TAG, "printer data return : " + SDKUtils.bytesToHexString(buffer));
                        switch (command) {
                            case ESC:
                                if (buffer[0] == 18) {
                                    return 0;
                                }

                                if ((buffer[0] & 32) > 0) {
                                    return -2;
                                }

                                if ((buffer[0] & 4) > 0) {
                                    return -3;
                                }

                                if ((buffer[0] & 64) > 0) {
                                    return -4;
                                }
                                break;
                            case TSC:
                                if ((buffer[0] & 32) > 0) {
                                    return 1;
                                }

                                if (buffer[0] == 0) {
                                    return 0;
                                }

                                if ((buffer[0] & 1) > 0) {
                                    return -3;
                                }

                                if ((buffer[0] & 4) > 0) {
                                    return -2;
                                }

                                if ((buffer[0] & 128) > 0) {
                                    return -4;
                                }

                                if ((buffer[0] & 2) > 0) {
                                    return -5;
                                }

                                if ((buffer[0] & 3) > 0) {
                                    return -6;
                                }

                                if ((buffer[0] & 5) > 0) {
                                    return -7;
                                }

                                if ((buffer[0] & 8) > 0) {
                                    return -8;
                                }

                                if ((buffer[0] & 9) > 0) {
                                    return -9;
                                }

                                if ((buffer[0] & 10) > 0) {
                                    return -10;
                                }

                                if ((buffer[0] & 11) > 0) {
                                    return -11;
                                }

                                if ((buffer[0] & 12) > 0) {
                                    return -12;
                                }

                                if ((buffer[0] & 13) > 0) {
                                    return -13;
                                }

                                if ((buffer[0] & 16) > 0) {
                                    return -14;
                                }
                                break;
                            case CPCL:
                                if (buffer[0] == 0) {
                                    return 0;
                                }

                                if ((buffer[0] & 1) > 0) {
                                    return 1;
                                }

                                if (buffer[0] == 2) {
                                    return -2;
                                }

                                if (buffer[0] == 4) {
                                    return -3;
                                }

                                if (buffer[0] == 6) {
                                    return -4;
                                }
                        }

                        return buffer[0] & 255;
                    } else {
                        return -1;
                    }
                }
            }
        } else {
            throw new IOException("Please connect Printer First...");
        }
    }

    public boolean getConnectStatus() {
        return this.isConn;
    }

    public int readData(byte[] bytes) throws IOException {
        return this.mmConnection != null ? this.mmConnection.bulkTransfer(this.mmEndIn, bytes, bytes.length, 1000) : -1;
    }

    public synchronized boolean closePort() {
        Log.e(TAG, "close");

        try {
            if (this.mUsbReceiver != null) {
                this.mContext.unregisterReceiver(this.mUsbReceiver);
                this.mUsbReceiver = null;
            }
        } catch (Exception var2) {
            Log.e(TAG, "close" + var2.getMessage());
        }

        this.mPrinterDevices = null;
        this.isConn = false;
        if (this.reader != null) {
            this.reader.cancel();
            this.reader.interrupt();
            this.reader = null;
        }

        this.command = null;
        if (this.usbManager != null) {
            this.usbManager = null;
        }

        if (this.mUsbDevice != null) {
            this.mUsbDevice = null;
        }

        if (this.mmIntf != null && this.mmConnection != null) {
            this.mmConnection.releaseInterface(this.mmIntf);
            this.mmConnection.close();
            this.mmConnection = null;
            this.mmIntf = null;
            this.mmEndIn = null;
            this.mmEndOut = null;
            return true;
        } else {
            return false;
        }
    }

    class IoReader extends Thread {
        private boolean isRun = true;

        public IoReader() {
        }

        public void cancel() {
            this.isRun = false;
        }

        public void run() {
            while(true) {
                try {
                    if (this.isRun) {
                        if (UsbPort.this.mmConnection == null) {
                            continue;
                        }

                        int len = UsbPort.this.mmConnection.bulkTransfer(UsbPort.this.mmEndIn, UsbPort.this.buffer, UsbPort.this.buffer.length, 2000);
                        if (len <= 0) {
                            continue;
                        }

                        synchronized(UsbPort.this.lock) {
                            final byte[] receive = SDKUtils.subBytes(UsbPort.this.buffer, 0, len);
                            UsbPort.this.byteArrayOutputStream.write(receive);
                            UsbPort.this.lock.notifyAll();
                            Thread.sleep(10L);
                            UIThreadManager.onUIThread(new Runnable() {
                                public void run() {
                                    UsbPort.this.callbackListener.onReceive(receive);
                                }
                            });
                            continue;
                        }
                    }
                } catch (Exception var6) {
                    if (UsbPort.this.callbackListener != null) {
                        UIThreadManager.onUIThread(new Runnable() {
                            public void run() {
                                LogUtils.e(UsbPort.TAG, "断开连接");
                                UsbPort.this.callbackListener.onDisconnect();
                            }
                        });
                    }
                }

                return;
            }
        }
    }
}
